package com.zwj.service.impl;

import com.zwj.config.FileProperties;
import com.zwj.entity.UserEntity;
import com.zwj.enums.SexEnum;
import com.zwj.mapper.StudentInfoMapper;
import com.zwj.mapper.UserMapper;
import com.zwj.service.StudentInfoService;
import com.zwj.utils.DataCheckUtils;
import com.zwj.utils.DateUtils;
import com.zwj.utils.FileUtils;
import com.zwj.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.List;

@Service
public class StudentInfoServiceIml implements StudentInfoService {
    private final StudentInfoMapper studentInfoMapper;
    private final UserMapper userMapper;
    private final Path imagePath;
    @Autowired
    public StudentInfoServiceIml(StudentInfoMapper studentInfoMapper, UserMapper userMapper, FileProperties fileProperties) {
        this.studentInfoMapper = studentInfoMapper;
        this.userMapper = userMapper;
        this.imagePath = Paths.get(fileProperties.getImage()).toAbsolutePath().normalize();
    }
    //查询学生个人信息
    @Override
    public Result queryStudentPersonalInfo(String id) {
        //数据校验
        DataCheckUtils.isNotBlank(id, "学生id不能为空!");
        QueryStudentPersonalInfoVo result = studentInfoMapper.queryStudentPersonalInfo(id);
        //判断查询结果
        if (result == null) {
            return Result.error("查询学生个人信息失败，可能你没有加入班级!");
        }
        if(result.getStudentSex().equals("0")){
            result.setStudentSex(SexEnum.FEMALE.getValue());
        }else{
            result.setStudentSex(SexEnum.MALE.getValue());
        }

        return Result.success(result);
    }

    //查询学生邮箱信息
    @Override
    public Result queryStudentEmail(String id) {
        //数据校验
        DataCheckUtils.isNotBlank(id, "学生id不能为空!");
        String result = studentInfoMapper.queryStudentEmail(id);
        //判断查询结果
        if (result == null) {
            return Result.error("查询学生邮箱信息失败，可能你的信息没有记录完，请联系管理员!");
        }
        return Result.success(result);
    }

    //查询学生电话信息
    @Override
    public Result queryStudentMobile(String id) {
        //数据校验
        DataCheckUtils.isNotBlank(id, "学生id不能为空!");
        String result = studentInfoMapper.queryStudentMobile(id);
        //判断查询结果
        if (result == null) {
            return Result.error("查询学生电话信息失败，可能你的信息没有记录完，请联系管理员!");
        }
        return Result.success(result);
    }

    //更新学生邮箱信息
    @Override
    public Result updateStudentEmail(String email,String id) {
        //数据校验
        DataCheckUtils.isNotBlank(email, "学生邮箱不能为空!");
        DataCheckUtils.isNotBlank(id, "学生id不能为空!");
        //插入数据
        UserEntity userEntity = new UserEntity();
        userEntity.setEmail(email);
        userEntity.setId(id);
        Integer result = studentInfoMapper.updateStudentEmail(userEntity);
        //判断插入结果
        if (result <= 0) {
            return Result.error("更新学生邮箱信息失败!");
        }
        return Result.success();
    }

    //更新学生电话信息
    @Override
    public Result updateStudentMobile(String mobileNo,String id) {
        //数据校验
        DataCheckUtils.isNotBlank(mobileNo, "学生电话不能为空!");
        DataCheckUtils.isNotBlank(id, "学生id不能为空!");
        //插入数据
        UserEntity userEntity = new UserEntity();
        userEntity.setMobileNo(mobileNo);
        userEntity.setId(id);
        Integer result = studentInfoMapper.updateStudentMobile(userEntity);
        //判断插入结果
        if (result <= 0) {
            return Result.error("更新学生电话信息失败!");
        }
        return Result.success();
    }

    //查询实训小组信息
    @Override
    public Result queryTrainingTeamInfo(String id) {
        //数据校验
        DataCheckUtils.isNotBlank(id, "学生id不能为空!");
        //查询实训小组信息
        List<QueryTrainingTeamInfoVo> result = studentInfoMapper.queryTrainingTeamInfo(id);
        //判断查询结果
        if (result == null) {
            return Result.error("查询实训小组信息失败，可能你没有加入实训小组，请联系班主任!");
        }

        for(QueryTrainingTeamInfoVo queryTrainingTeamInfoVo : result){
            String cid = queryTrainingTeamInfoVo.getId();
            String courseId = queryTrainingTeamInfoVo.getCourseId();
            String courseName = queryTrainingTeamInfoVo.getCourseName();
            //查询课程的签到和签退时间
            List<QueryCourseSignTimeVo> row = studentInfoMapper.queryCourseSignTime(courseId);
            String date = ""; //记录标椎学时 date
            long h = 0; //记录查询的小时
            long m = 0;//记录查询的分钟
            for(QueryCourseSignTimeVo queryCourseSignTimeVo:row){
                //算出标椎学时  签退时间-签到时间
                long d =  DateUtils.dateSubtractionHour(queryCourseSignTimeVo.getSignInTime(),queryCourseSignTimeVo.getSignOutTime());
                d=d/1000;
                m = m + (d/60)%60;
                h = h + ((d/60)/60)%60;
            }
            double minute = m;
            date = h + minute/60 + "";
            System.out.println("date:" + date);
            //判断项目组中的成员是否都在该课程中，在就加上课程名称和标椎学时，不在就为空
            //查询课程中所有学生id
            List<QueryCourseStudentsVo> effect = studentInfoMapper.queryCourseStudents(cid);
            for(QueryCourseStudentsVo queryCourseStudentsVo:effect){
                System.out.println("getStudentId:" + queryTrainingTeamInfoVo.getStudentId());
                System.out.println("getTeamMemberId:" + queryCourseStudentsVo.getTeamMemberId());
                System.out.println(queryTrainingTeamInfoVo.getStudentId().equals(queryCourseStudentsVo.getTeamMemberId()));
                if(queryTrainingTeamInfoVo.getStudentId().equals(queryCourseStudentsVo.getTeamMemberId())){
                    System.out.println("hahaha");
                    queryTrainingTeamInfoVo.setCourseId(courseId);
                    queryTrainingTeamInfoVo.setCourseName(courseName);
                    queryTrainingTeamInfoVo.setJobTime(date);
                    break;
                }else{
                    queryTrainingTeamInfoVo.setCourseId(null);
                    queryTrainingTeamInfoVo.setCourseName(null);
                    queryTrainingTeamInfoVo.setJobTime(null);
                }
            }
        }
        return Result.success(result);
    }

    //头像上传
    @Override
    public Result uploadFile(MultipartFile file) {
        try {
            if(file.isEmpty()){
                return Result.error("上传文件为空");
            }
            String fileName = file.getOriginalFilename();
            String[] fn = fileName.split("\\.");
            if(fn.length<2){
                return Result.error("文件名格式不符合");
            }
            String fileExtension = fn[fn.length-1];
            System.out.println("后缀:" + fileExtension);
            System.out.println(!FileUtils.isFileExtension(fileExtension));
            if (!"jpg".equals(fileExtension)&&!"png".equals(fileExtension)) return Result.error("上传文件失败，含有不被接受的文件名");
            String os = System.getProperty("os.name");
            File fileRealPath;   //文件存放地址
            if (os.toLowerCase().startsWith("win")) {  //windows系统
                fileRealPath = new File(FileUtils.mkdirshead(new ApplicationHome(getClass())));
            }else{//linux系统
                fileRealPath = new File(imagePath.toUri());
                //判断文件夹是否存在
                if(!fileRealPath.exists()){
                    //不存在，创建
                    fileRealPath.mkdirs();
                }
//                fileRealPath = new File(FileUtils.mkdirshead(new ApplicationHome(getClass()),"/image/"));
            }
            String name = null;
            File resultPath =null;
            int i;
            for (i = 0; i < 3; i += 1) {
                //获取文件名称
                name = FileUtils.getFileName();
                //创建文件存放地址
                resultPath = new File(fileRealPath+"/"+name+"."+fileExtension);
                if (!resultPath.exists()){
                    break;
                }
            }
            if (i >= 3) {
                return Result.error("上传文件失败，失败原因生成文件名失败");
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            file.transferTo(resultPath);
            System.out.println("absolutePath:"+fileRealPath.getCanonicalPath());
            System.out.println("resultPath:"+resultPath.getCanonicalPath());
            UserEntity userEntity = new UserEntity();
            userEntity.setLogoUrl(resultPath.getCanonicalPath()+name+"."+fileExtension);
            int row = userMapper.insert(userEntity);
            return Result.success(resultPath.getCanonicalPath()+name+"."+fileExtension);
        }catch (Exception e){
            return Result.error("上传文件失败");
        }
    }
}
